package com.example.demo.controller.order;

import com.example.demo.controller.BaseController;
import com.example.demo.domain.AjaxResult;
import com.example.demo.domain.order.Payment;
import com.example.demo.domain.order.SaleOrder;
import com.example.demo.domain.vip.Vip;
import com.example.demo.service.order.PaymentService;
import com.example.demo.service.order.SaleOrderService;
import com.example.demo.service.vip.VipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/payment")
public class PaymentController extends BaseController {
    @Autowired
    private PaymentService paymentService;

    @Autowired
    private SaleOrderService saleOrderService;

    @Autowired
    private VipService vipService;
    @GetMapping("/add/{orderId}")
    public String pay(@PathVariable("orderId") Integer orderId, ModelMap map){
        SaleOrder saleOrder = saleOrderService.selectByPrimaryKey(orderId);
        if(saleOrder.getVipId()!=null){
            Vip vip = vipService.selectByPrimaryKey(saleOrder.getVipId());
            map.put("vip",vip);
        }
        map.put("saleOrder",saleOrder);
        return "cashier/Payment";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(Payment payment,Integer vipId){
        //如果选择的是储蓄卡支付
        if(payment.getPayType() == 4 && vipId!=null) {
            //查找余额
            Vip vip = vipService.selectByPrimaryKey(vipId);
            //比较余额大小
            if(vip.getVipAccount().compareTo(payment.getPayAmount())>=0 ){
            vip.setVipAccount(vip.getVipAccount().subtract(payment.getPayAmount()));
            //更新余额
            vipService.updateByPrimaryKeySelective(vip);
            }
        }
        return toAjax(paymentService.insert(payment));

    }

}